package org.jeecg.modules.exTenderFileClariModi.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.json.JsonObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FileUtil;
import org.jeecg.common.util.dynamic.db.DataSourceCachePool;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exChargeSetting.entity.ExChargeSetting;
import org.jeecg.modules.exProject.constant.ExProjectStepEnum;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.entity.ExProjectExtend;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.service.IExProjectExtendService;
import org.jeecg.modules.exProject.service.IExProjectService;
import org.jeecg.modules.exProject.service.IExSectionService;
import org.jeecg.modules.exTender.entity.ExTenderList;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.service.IExTenderAnnQuaInqueryAnnService;
import org.jeecg.modules.exTenderFile.entity.Chapter;
import org.jeecg.modules.exTenderFile.entity.ExTenderFileDetail;
import org.jeecg.modules.exTenderFile.service.IChapterService;
import org.jeecg.modules.exTenderFile.service.IExTenderFileDetailService;
import org.jeecg.modules.exTenderFile.vo.ChapterTree;
import org.jeecg.modules.exTenderFileClariModi.entity.ExTenderFileClariModi;
import org.jeecg.modules.exTenderFileClariModi.service.IExTenderFileClariModiService;
import org.jeecg.modules.exTenderFileSetVariable.entity.ExTenderFileSetVariable;
import org.jeecg.modules.exTenderFileSetVariable.service.IExTenderFileSetVariableService;
import org.jeecg.modules.system.entity.SysDataSource;
import org.jeecg.modules.system.entity.SysDepartRole;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.entity.SysPermissionDataRule;
import org.jeecg.modules.system.model.SysPermissionTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 招标文件
 * @Author: jeecg-boot
 * @Date: 2024-09-11
 * @Version: V1.0
 */
@Api(tags = "招标文件")
@RestController
@RequestMapping("/exTenderFileClariModi/exTenderFileClariModi")
@Slf4j
public class ExTenderFileClariModiController extends JeecgController<ExTenderFileClariModi, IExTenderFileClariModiService> {
    @Autowired
    private IExTenderFileClariModiService exTenderFileClariModiService;
    @Autowired
    private IExProjectService iExProjectService;
    @Autowired
    private IExSectionService sectionService;

    @Autowired
    private IExTenderAnnQuaInqueryAnnService annQuaInqueryAnnService;

    @Autowired
    private IExProjectExtendService exProjectExtendService;
    @Autowired
    private IChapterService chapterService;
    @Autowired
    private IExTenderFileSetVariableService exTenderFileSetVariableService;
    @Autowired
    private IExTenderFileDetailService exTenderFileDetailService;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;


    /**
     * 分页列表查询
     *
     * @param exTenderFileClariModi
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "招标文件-分页列表查询")
    @ApiOperation(value = "招标文件-分页列表查询", notes = "招标文件-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExTenderFileClariModi>> queryPageList(ExTenderFileClariModi exTenderFileClariModi,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        QueryWrapper<ExTenderFileClariModi> queryWrapper = QueryGenerator.initQueryWrapper(exTenderFileClariModi, req.getParameterMap());
        Page<ExTenderFileClariModi> page = new Page<ExTenderFileClariModi>(pageNo, pageSize);
        IPage<ExTenderFileClariModi> pageList = exTenderFileClariModiService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param exTenderFileClariModi
     * @return
     */
    @AutoLog(value = "招标文件-添加")
    @ApiOperation(value = "招标文件-添加", notes = "招标文件-添加")
    //@RequiresPermissions("org.jeecg.modules:ex_tender_file_clari_modi:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExTenderFileClariModi exTenderFileClariModi) {
        exTenderFileClariModiService.saveTenderFile(exTenderFileClariModi);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exTenderFileClariModi
     * @return
     */
    @AutoLog(value = "招标文件-编辑")
    @ApiOperation(value = "招标文件-编辑", notes = "招标文件-编辑")
    //@RequiresPermissions("org.jeecg.modules:ex_tender_file_clari_modi:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExTenderFileClariModi exTenderFileClariModi) {
        exTenderFileClariModiService.updateById(exTenderFileClariModi);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招标文件-通过id删除")
    @ApiOperation(value = "招标文件-通过id删除", notes = "招标文件-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:ex_tender_file_clari_modi:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        exTenderFileClariModiService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "招标文件-批量删除")
    @ApiOperation(value = "招标文件-批量删除", notes = "招标文件-批量删除")
    //@RequiresPermissions("org.jeecg.modules:ex_tender_file_clari_modi:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.exTenderFileClariModiService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "招标文件-通过id查询")
    @ApiOperation(value = "招标文件-通过id查询", notes = "招标文件-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExTenderFileClariModi> queryById(@RequestParam(name = "id", required = true) String id) {
        ExTenderFileClariModi exTenderFileClariModi = exTenderFileClariModiService.getById(id);
        if (exTenderFileClariModi == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(exTenderFileClariModi);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param exTenderFileClariModi
     */
    //@RequiresPermissions("org.jeecg.modules:ex_tender_file_clari_modi:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExTenderFileClariModi exTenderFileClariModi) {
        return super.exportXls(request, exTenderFileClariModi, ExTenderFileClariModi.class, "招标文件");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("ex_tender_file_clari_modi:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ExTenderFileClariModi.class);
    }

    /**
     * 招标文件下载
     *
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/download/zbFile")
    public void download(HttpServletResponse response, ExTenderFileClariModi exTenderFileClariModi) throws Exception {
        if (exTenderFileClariModi == null || ObjectUtil.isEmpty(exTenderFileClariModi.getSectionId())) {
            throw new Exception("参数缺失");
        }

        ExSection exSection = sectionService.getById(exTenderFileClariModi.getSectionId());
        if (exSection == null) {
            throw new Exception("参数错误");
        }
        String projectId = exSection.getProjectId();
        String sectionId = exSection.getId();
        List<Chapter> chapterList = getChapterList(sectionId);
        if (CollectionUtil.isEmpty(chapterList)) {
            throw new Exception("没有找到标段目录数据");
        }

        LambdaQueryWrapper<ExTenderFileClariModi> queryWrapper = new LambdaQueryWrapper<ExTenderFileClariModi>();
        queryWrapper.eq(ExTenderFileClariModi::getSectionId, sectionId);
        ExTenderFileClariModi tenderFileClariModi = exTenderFileClariModiService.getOne(queryWrapper);
        if (tenderFileClariModi == null) {
            throw new Exception("未找到招标文件");
        }
        // 如果招标文件已存在，则直接下载，否则创建
        if(StringUtils.isNotBlank(tenderFileClariModi.getUrl())){
            FileUtil.dowloadFile(new File(tenderFileClariModi.getUrl()),response);
            return;
        }


        /**项目基础信息组装（project.json文件写入内容）***/
        ExProject exProject = iExProjectService.getById(projectId);
        ExProjectExtend exprojectExtend = exProjectExtendService.getExprojectExtend(projectId);
        String tenderOrgName = "";//招标机构名称
        if (exprojectExtend != null) {
            tenderOrgName = exprojectExtend.getTenderOrgName();
        }
        Date startDate = new Date();
        String noticeSendTime = DateUtils.date2Str(startDate,DateUtils.datetimeFormat.get());

        Map<String, Object> map = new HashMap<>();
        //第一部分 项目信息
        Map<String, Object> projectMap = new HashMap<>();
        projectMap.put("projectName", exProject.getProjectName());
        projectMap.put("projectCode", exProject.getProjectCode());
        projectMap.put("sectionId", exSection.getId());
        projectMap.put("sectionCode", exSection.getBidSectionCode());
        projectMap.put("sectionName", exSection.getBidSectionName());
        map.put("projectInfo", projectMap);
        //定义投标工具展示项目内容列表
        List<String> showProjectInfoList = new ArrayList<>();
        showProjectInfoList.add("招标/采购项目编号: " + exProject.getProjectCode());
        showProjectInfoList.add("公告日期: " + noticeSendTime); // 需要取公告日期
        showProjectInfoList.add("招标机构: " + tenderOrgName); //招标机构名称
        showProjectInfoList.add("开标/开启地点: " + "开标一室");
        showProjectInfoList.add("开标/开启时间: " + noticeSendTime);
        showProjectInfoList.add("联系人: " + exProject.getContactor());
        showProjectInfoList.add("联系电话: " + exProject.getContactInformation());
        map.put("showProjectInfoList", showProjectInfoList);

        List<ChapterTree> chapterTrees = chapterService.treeList(sectionId);
        // 第二部分 招标文件树形目录
        map.put("tree", chapterTrees);

        // 第三部分 变量信息
        map.put("variable", getSetVariableList(sectionId));

        /****各个文件写入，打包zip下载***/
        //定义招标文件目录 :/opt/upFiles/zbFile/projectCode/sectionCode/
        String zbFileBaseDir = uploadpath + File.separator + "zbFile"  + File.separator+ exProject.getProjectCode() +File.separator  + exSection.getBidSectionCode();
        // 本次生成文件存放目录 /opt/upFiles/zbFile/projectCode/sectionCode/uuid/
        String zfFilePath = zbFileBaseDir + File.separator + UUID.randomUUID().toString();

        File zfFilePathDir = new File(zfFilePath);
        if (!zfFilePathDir.exists()) {
            zfFilePathDir.mkdirs();
        }
        //第一 先创建项目信息文件，并写入文件 project.json
        File projectInfoFile = new File(zfFilePath + File.separator + "project.json");
        if (!projectInfoFile.exists()) {
            projectInfoFile.createNewFile();
        }
        try (FileWriter fileWriter = new FileWriter(projectInfoFile);
             BufferedWriter out = new BufferedWriter(fileWriter)
        ) {
            out.write(JSON.toJSONString(map));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 第二分别创建招标文件每个目录对应的html或word文件(需要根据招标类型创建对应文件，如投标函创建.html 如工程量清单，则创建对应附件)
        if (CollectionUtil.isNotEmpty(chapterList)) {
        //    List<String> chapterIdList = chapterList.stream().map(Chapter::getId).collect(Collectors.toList());
        //    List<ExTenderFileDetail> tenderFileDetailList = getTenderFileDetailList(chapterIdList);
            for (int i = 0; i < chapterList.size(); i++) {
                String fileName = "";
                String chapterId = chapterList.get(i).getId();
                ExTenderFileDetail exTenderFileDetail = exTenderFileDetailService.getOne(new LambdaQueryWrapper<ExTenderFileDetail>().eq(ExTenderFileDetail::getCategoryId, chapterId));
                fileName = chapterList.get(i).getName();
                String fileContent = exTenderFileDetail.getContent();
               // Optional<Chapter> optionalChapter = chapterList.stream().filter(item -> item.getId().equals(exTenderFileDetail.getCategoryId())).findFirst();
//                if (optionalChapter.isPresent()) {
//                    fileName = optionalChapter.get().getName();
//                }
                //第一 先创建项目信息文件，并写入文件 project.json
                File tenderFile = new File(zfFilePath + File.separator + fileName + ".html");
                tenderFile.createNewFile();
                try (FileWriter fileWriter = new FileWriter(tenderFile);
                     BufferedWriter out = new BufferedWriter(fileWriter)
                ) {
                    out.write(fileContent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        // 最后将上述文件夹打包zip
        /***上述文件生成后，开始打包再下载***/
        // 定义打包zip文件
        String fileName = exProject.getProjectName() +"_" + exSection.getBidSectionName();
        String zipFile = fileName + ".zip";
        File file = new File(zipFile);
        FileOutputStream fos = new FileOutputStream(file);
        FileUtil.toZip(zfFilePath, fos, response);
//        FileUtil.dowloadZip(file, response);
 //       file.delete();

        // 最后zip重命名ZBF
        String zbfFile = zbFileBaseDir + File.separator + fileName +".ZBF";
        File newFile = new File(file.getParent(), zbfFile);
        file.renameTo(newFile);
        FileUtil.dowloadFile(newFile,response);
        // 最后更新招标文件url
        tenderFileClariModi.setUrl(zbfFile);
        exTenderFileClariModiService.updateById(tenderFileClariModi);
    }

    private void addToZip(ZipOutputStream zipOutputStream, InputStream inputStream, String fileName) throws IOException {
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            zipOutputStream.write(buffer, 0, bytesRead);
        }
        zipOutputStream.closeEntry();
        inputStream.close();
    }

    /**
     * 把指定URL后的字符串全部截断当成参数
     * 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     *
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    private List<Chapter> getChapterList(String sectionId) {
        LambdaQueryWrapper<Chapter> query = new LambdaQueryWrapper<Chapter>().eq(Chapter::getSectionId, sectionId);
        return chapterService.list(query);
    }

    private List<ExTenderFileSetVariable> getSetVariableList(String sectionId) {
        LambdaQueryWrapper<ExTenderFileSetVariable> query = new LambdaQueryWrapper<ExTenderFileSetVariable>().eq(ExTenderFileSetVariable::getSectionId, sectionId);
        return exTenderFileSetVariableService.list(query);
    }

    private List<ExTenderFileDetail> getTenderFileDetailList(List<String> categoryIds) {
        LambdaQueryWrapper<ExTenderFileDetail> query = new LambdaQueryWrapper<ExTenderFileDetail>().in(ExTenderFileDetail::getCategoryId, categoryIds);
        return exTenderFileDetailService.list(query);
    }


}
